<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-button type="primary" @click="addDialogVisible = true"
          >添加角色</el-button
        >
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolelist" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @click="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @click="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @click="removeRightById(scope.row, item3.id)"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="编号" width="60">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" icon="el-icon-delete"  @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-s-tools"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色信息对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%" @close="setRightDialogClosed"
    >
    <!-- 树形控件 -->
      <el-tree :data="rightslist" :props="treeProps" 
      :default-checked-keys="defKeys" ref="treeRef"
      node-key="id" default-expand-all show-checkbox></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editFrom"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolelist">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      
      setRightDialogVisible:false,//控制分配权限页面的显示
      //所有角色列表数据
      rolelist: [],
      addDialogVisible: false, //控制添加页面的显示
      editDialogVisible: false, //控制修改页面的显示
      addForm: {
        roleName: "", //角色名称
        roleDesc: "", //角色描述
      },
      //修改的对象
      editFrom: {},
      //添加表单验证
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色备注", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 15 个字符", trigger: "blur" },
        ],
      },
      //修改表单验证
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色备注", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 15 个字符", trigger: "blur" },
        ],
      },
      rightslist:{},//权限列表对象
      treeProps:{
        //树形控件的属性绑定
        label:'authName',
        children:'children'
      },
      //默认选中的权限节点
      defKeys:[],
      roleId:''//当前即将分配权限的Id
    };
  },
  created() {
    this.getRolestList();
  },
  methods: {
    //获取所有角色的列表
    async getRolestList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolelist = res.data;
      console.log(this.rolelist);
    },
    //监听用户添加对话框的关闭事件
    addDialogClosed() {
      //resetFields():对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.addFormRef.resetFields();
    },
    //添加角色
    addRoles() {
      //添加预验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status != 201) {
          this.res.$message.error("添加角色失败!");
        }
        this.$message.success("添加用户成功!");
        //关闭页面
        this.addDialogVisible = false;
        //刷新页面
        this.getRolestList();
      });
    },
    //查询要修改的角色信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status != 200) {
        return this.$message.error("查询角色信息失败!");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    //重置修改页面
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改角色信息并提交
    editRolelist() {
      //预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editFrom.roleId,
          {
            roleName: this.editFrom.roleName,
            roleDesc: this.editFrom.roleDesc,
          }
        );
        console.log(this.editFrom.id);
        if (res.meta.status != 200) {
          return this.$message.error("修改用户角色失败!");
        }
        this.$message.success("修改用户角色成功!");
        //隐藏对话框
        this.editDialogVisible = false;
        //刷新页面
        this.getRolestList();
      });
    },
    //根据Id删除对应的权限
    async removeRightById(role, rightId) {
      console.log("触发了removeRightById");
      //弹框提示用户是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除");
      }
      //获取删除权限的id
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败!");
      }

      //this.getRolestList();
      role.children = res.data;
      return this.$message.success("删除成功!");
    },
    //展示分配权限对话框
    async showSetRightDialog(role){
      //获取当前的角色ID
      this.roleId = role.id;
      //获取所有权限列表
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status!=200){
        return this.res.$message.error('获取权限数据失败')
      }
      this.rightslist = res.data
      console.log(this.rightslist);
      //递归获取三级节点的Id
      this.getLeafKeys(role,this.defKeys)

      this.setRightDialogVisible =  true;
    },
    //如果当前node节点不包含children属性,则是三级节点
    getLeafKeys(node,arr){
      //如果当前node节点不包含children属性，则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item,arr)
      )
    },
    //关闭分配权限对话框的关闭事件
    setRightDialogClosed(){
      this.defKeys = [];
    },
    //点击为角色分配权限
    async allotRights(){
      const keys= [
        //tree属性组件
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')//拼接字符串
      const{data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })
      if(res.meta.status !=200){
        return this.$message.error("分配角色权限失败!")
      }
      this.$message.success("分配角色权限成功!");
      this.getRolestList()
      this.setRightDialogVisible = false;
    },
    //删除角色
    async removeUserById(id){
      //弹窗询问用户是否删除数据
     const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err)=>err);
        if(confirmResult !== "confirm"){
           this.$message.info("已取消删除");
          return;
        } 
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败!");
        }
        this.$message.success("删除角色成功");
        this.getRolestList();
    }
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>